package com.urbane.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus 自动填充处理器
 * <p>
 * 用于自动填充创建时间、更新时间、创建人、版本号等字段
 * 需注册为 Spring Bean
 * </p>
 */
@Slf4j
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    /**
     * 插入时自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");
        // 严格填充：字段必须存在，类型必须匹配
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        // 默认版本号 1
        this.strictInsertFill(metaObject, "version", Integer.class, 1);

        // 默认未删除
        this.strictInsertFill(metaObject, "deleted", Integer.class, 0);

        // 【可选】填充创建人、租户ID 等
        // Long currentUserId = UserContext.getCurrentUserId(); // 自定义上下文工具类
        // this.strictInsertFill(metaObject, "createUserId", Long.class, currentUserId);
        // this.strictInsertFill(metaObject, "tenantId", Long.class, TenantContext.getCurrentTenantId());
    }

    /**
     * 更新时自动填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        // 【可选】填充更新人
        // Long currentUserId = UserContext.getCurrentUserId();
        // this.strictUpdateFill(metaObject, "updateUserId", Long.class, currentUserId);
    }
}

// 此处内容参考 Mybatis-Plus 官网，自动填充字段 https://baomidou.com/guides/auto-fill-field/